<template>
  <a-drawer
      :visible="visible"
      :title="title"
      placement="right"
      @close="btnCancels"
      :width="$store.getters.isMobile ? '100%' : 450"
      :keyboard="false"
      :body-style="{
      height: 'calc(100% - 110px)',
      boxSizing: 'border-box',
    }"
  >
    <a-form
        ref="formRef"
        :model="formState"
        :rules="rules"
        @finish="btnok"
        layout="vertical"
    >
      <!--     @finish="handleOk"  -->
      <a-form-item label="姓名" name="name">
        <a-input v-model:value="formState.name" placeholder="请填写姓名"/>
      </a-form-item>
      <a-form-item label="电话" name="phone">
        <a-input
            type="tel"
            v-model:value="formState.phone"
            placeholder="请填写电话"
        />
      </a-form-item>
      <a-form-item label="渠道类型" name="source">
        <a-select
            v-model:value="formState.source"
            :options="sourceOptions"
            placeholder="请选择渠道类型"
            @change="changeSource"
        ></a-select>
      </a-form-item>
      <a-form-item label="所属公司" name="channel_company_id" v-if="is_company">
        <a-select
            v-model:value="formState.channel_company_id"
            :options="companyOptions"
            show-search
            :filterOption="filterOption"
            placeholder="所属公司"
            @change="changeCompany"
            allowClear
        ></a-select>
      </a-form-item>

      <a-form-item label="绑定项目" name="village_id" v-if="!isAllVillage">
        <a-select
            v-model:value="formState.village_id"
            :options="optionsBuild"
            mode="multiple"
            placeholder="请选择项目"
            @change="handleChange"
        ></a-select>
      </a-form-item>


      <a-form-item label="所属城市/区域">
        <a-cascader
            v-model:value="area"
            :options="areaOptions"
            placeholder="请选择城市/区域"
            change-on-select
            :load-data="loadAreaData"
            @change="areaChange"
            :disabled="formState.channel_company_id!=undefined&&is_company"
        />
      </a-form-item>
      <a-form-item label="邮箱" name="email">
        <a-input
            type="email"
            v-model:value="formState.email"
            placeholder="请填写电子邮箱"
        />
      </a-form-item>
      <a-form-item label="通讯地址" name="address">
        <a-textarea
            v-model:value="formState.address"
            placeholder="请填写通讯地址"
            :rows="4"
        />
      </a-form-item>

      <a-form-item label="开户行" name="bank" v-if="!is_company">
        <a-input
            placeHolder="请填写开户行"
            v-model:value="formState.bank"
            :disabled="formState.channel_company_id!=undefined&&is_company"
        ></a-input>
      </a-form-item>

      <a-form-item label="收款账号" name="bank_account" v-if="!is_company">
        <a-input
            type="tel"
            placeHolder="请填写收款账号"
            v-model:value="formState.bank_account"
            :disabled="formState.channel_company_id!=undefined&&is_company"
        ></a-input>
      </a-form-item>

      <a-form-item label="补充材料">
        <a-upload
            :action="imgAction"
            v-model:file-list="fileList"
            :multiple="false"
            accept="image/*"
            name="image"
            list-type="picture-card"
            :headers="{ 'org-token': $store.getters.token }"
            :data="{ dir: 'org_village' }"
            @change="handleUploadChange"
        >
          <div v-if="fileList.length < 3">
            <PlusOutlined/>
            <div style="padding-top: 4px">上传</div>
          </div>
        </a-upload>
      </a-form-item>


      <div class="drawer-footer">
        <a-button class="clear mr-10" @click.prevent="btnCancels"
        >取消
        </a-button
        >
        <a-button type="primary" html-type="submit">保存</a-button>
        <!-- html-type="submit" -->
      </div>
    </a-form>
  </a-drawer>
</template>

<script>
import {
  defineComponent,
  ref,
  toRaw,
  reactive,
  computed,
  watch,
  toRefs,
} from "vue";
import request from "../../../../common/utils/request";
import utils from "../../../../common/utils/utils";
import {message} from "ant-design-vue";
import {PlusOutlined, DeleteOutlined, QuestionCircleOutlined} from "@ant-design/icons-vue";

export default defineComponent({
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    id: {
      type: [Number, String],
      default: 0,
    },
    optionsBuild: {
      type: Array,
      default: () => [],
    },
  },
  components: {
    QuestionCircleOutlined,
    PlusOutlined,
    DeleteOutlined,
  },
  setup(props, context) {
    const resetInfos = () => {
      context.emit("cancel");
      formRef.value.resetFields();
    };

    const btnCancels = () => {
      resetInfos();
    };

    const handleChange = (val) => {
      console.log(val);
    };

    const state = reactive({
      is_company: false,
    })
    const formRef = ref();
    const area = ref([]);
    const formState = reactive({
      name: "",
      phone: "",
      company: "",
      channel_company_id: undefined, //所属公司
      email: "",
      address: "",
      id: "",
      village_id: [],
      source: undefined,
      bank: "",
      bank_account: "",
      extra: [],
      isAllProject: false,
    });

    const fileList = ref([]);
    const btnok = () => {
      console.log(props.id);
      console.log(fileList.value);
      formState.extra = [];
      if (fileList.value.length > 0) {
        formState.extra = fileList.value.map((item) => {
          return item.url;
        });
      }
      if (!state.is_company) {
        delete formState.channel_company_id;
      }
      if (props.id && props.id != 0) {
        formState.area = areas;
        formState.id = props.id;
        request
            .put("/org", "/business/customer/channel", formState)
            .then((res) => {
              message.success("编辑成功");
              context.emit("btnOk");
              formRef.value.resetFields();
            });
        return;
      }
      formState.area = areas;
      request
          .post("/org", "/business/customer/channel", formState)
          .then((res) => {
            context.emit("btnOk");
            formRef.value.resetFields();
          });
    };

    const isAllVillage = ref(false)
    const rules = ref({
      name: [
        {
          required: true,
          message: "请输入租客姓名",
          trigger: "blur",
        },
      ],
      area: [
        {
          required: true,
          message: "请选择城市/区域",
          trigger: "blur",
        },
      ],
      phone: [
        {
          required: true,
          validator: (rules, value) => utils.phoneAndTelValidator(rules, value),
        },
      ],
      source: [
        {
          required: true,
          message: "请选择渠道",
          trigger: "blur",
        },
      ],
      village_id: [
        {
          required: false,
          message: "请选择项目",
          trigger: "blur",
        },
      ],
      company: [
        {
          required: false,
          message: "请填写公司名称",
          trigger: "blur",
        },
      ],
      email: [
        {
          required: false,
          message: "请填写邮箱",
          trigger: "blur",
        },
      ],
      address: [
        {
          required: false,
          message: "请填写通讯地址",
          trigger: "blur",
        },
      ],
    });

    // 所属城市区域
    const areaOptions = ref([]);
    let areas = {
      provinceId: "",
      provinceName: "",
      cityId: "",
      cityName: "",
      districtId: "",
      districtName: "",
      streetId: "",
      streetName: "",
    };
    const areaChange = (areaChangeValue, value) => {
      if (value) {
        areas.provinceId = value[0]?.value;
        areas.provinceName = value[0]?.label;
        areas.cityId = value[1]?.value;
        areas.cityName = value[1]?.label;
        areas.districtId = value[2]?.value;
        areas.districtName = value[2]?.label;
        areas.streetId = value[3]?.value;
        areas.streetName = value[3]?.label;

      } else {
        Object.keys(areas).forEach((key) => {
          areas[key] = "";
        });
      }
    };
    // 加载已选择列表
    // 省
    const getArea = () => {
      utils.getAreaOptions(1).then((list) => {
        areaOptions.value = list;
      });
    };

    // 动态加载省市区信息
    const loadAreaData = (selectedOptions) => {
      const targetOption = selectedOptions[selectedOptions.length - 1];
      targetOption.loading = true; // load options lazily
      if (targetOption.level < 4) {
        utils
            .getAreaOptions(targetOption.level + 1, {
              id: targetOption.value,
              leafLevel: 4,
            })
            .then((res) => {
              if (res.length) {
                targetOption.children = res;
              } else {
                targetOption.isLeaf = true;
              }
              targetOption.loading = false;
            });
      }
    };

    // 渠道类型
    const sourceOptions = ref([]);
    const sourceOptionsList = () => {
      request
          .get("/org", "/business/customer/channel/sourceList")
          .then((res) => {
            sourceOptions.value = res.list.map((item) => {
              return {
                value: item.id,
                label: item.source,
                is_company: item.is_company == 1 ? true : false
              };
            });
          });
    };


    const setArea = (value) => {
      const {provinceId, cityId, districtId, streetId} = value;
      areas = value;
      if (provinceId) {
        area.value.push(provinceId);
        utils.getAreaOptions(1).then((list) => {
          areaOptions.value = list;
          let index = list.findIndex((item) => item.value == provinceId);
          if (cityId && index > -1) {
            area.value.push(cityId);
            let province = areaOptions.value[index];
            utils.getAreaOptions(2, {id: provinceId}).then((cityList) => {
              if (cityList.length) {
                province.children = cityList;
                index = cityList.findIndex((item) => item.value == cityId);
                if (districtId && index > -1) {
                  area.value.push(districtId);
                  let city = province.children[index];
                  utils
                      .getAreaOptions(3, {id: cityId})
                      .then((districtList) => {
                        if (districtList.length) {
                          city.children = districtList;
                          index = districtList.findIndex(
                              (item) => item.value == districtId
                          );
                          if (streetId && index > -1) {
                            area.value.push(streetId);
                            let district = city.children[index];
                            utils
                                .getAreaOptions(4, {id: districtId})
                                .then((streetList) => {
                                  if (streetList.length) {
                                    district.children = streetList;
                                    index = streetList.findIndex(
                                        (item) => item.value == streetId
                                    );
                                  } else {
                                    district.isLeaf = true;
                                  }
                                });
                          }
                        } else {
                          city.isLeaf = true;
                        }
                      });
                }
              } else {
                province.isLeaf = true;
              }
            });
          }
        });
      }

    }

    // 详情列表
    let detail = {};
    const getChannelList = () => {
      request
          .get("/org", "/business/customer/channel/get", {id: props.id})
          .then((res) => {
            detail = res.detail;

            setModelRef(detail);
            if (detail.area) {
              setArea(detail.area)
            }
          });
    };
    const setModelRef = (state) => {
      for (let key in state) {
        if (key == "source" && state[key]) {
          formState.source = state[key].id;
        } else if (key == "channel_company_id") {
          formState.channel_company_id = state[key] == 0 ? undefined : state[key];
        } else {
          formState[key] = state[key];
        }
        fileList.value = [];
        if (formState?.extra?.length > 0) {
          fileList.value = formState?.extra.map((item) => {
            return {
              url: item.url,
            };
          });
        }
      }

      console.log(formState);
    };

    const companyOptions = ref([])
    const getCompanyList = () => {
      request.get("/org", "/user/channel/channelCompanyIndex").then(res => {

        companyOptions.value = res.data.map(item => {
          const is_expire = item.is_expire_txt == true
          return {
            label: is_expire ? `${item.name} (协议到期)` : item.name,
            value: item.id,
            disabled: is_expire,
            ...item
          }
        })
      })
    }

    const changeCompany = (val) => {
      console.log(val)
      const getItem = companyOptions.value.filter(item => {
        return item.value == val
      })
      if (getItem.length == 1) {
        const item = getItem[0]
        console.log(item)
        if (item.address) {
          area.value = [];
          setArea(item.address);
        }
        formState.company = item.name;
        formState.bank = item.opening_bank;
        formState.bank_account = item.receiving_account;
      }
    }

    const changeSource = (val, option) => {
      state.is_company = option.is_company
      if (!option.is_company) {
        formState.channel_company_id = undefined
      }
    }


    const title = computed(() => {
      return props.id ? "编辑渠道联系人" : "新建渠道联系人";
    });

    const getProjectSetting = () => {
      request.get("/org", "/user/channel/getVillageIsAll").then(res => {
        isAllVillage.value = res.data == 0 ? false : true
        rules.value.village_id[0].required = !isAllVillage.value
      })
    }

    watch(
        () => props.visible,
        (val) => {
          if (val) {
            sourceOptionsList();
            getProjectSetting()
            getArea();
            getCompanyList()
            if (props.id) {
              getChannelList();
            }
          } else {
            areaOptions.value = [];
            detail = {};
            area.value = [];
            fileList.value = [];
          }
        }
    );

    // 上传
    const handleUploadChange = (info) => {
      let resFileList = [...info.fileList];
      if (resFileList.length > 0) {
        // console.log(resFileList, "取最后一条数据之前");
        resFileList = resFileList.slice(-1);
        // console.log(resFileList, "取最后一条数据");

        resFileList = resFileList.map((file) => {
          if (file.response) {
            if (file.response.code == 1000) {
              file.url = file.response.data.fileUrl;

              // fileList.value.push({
              //   name: file.name,
              //   url: file.fileUrl,
              // });
            } else {
              message.warning(file.response.msg);
            }
          }
          return file;
        });

        console.log(resFileList, "最终数据");

        console.log(fileList.value);
      }
    };

    const filterOption = (string, any) => {
      return any.label.toLowerCase().indexOf(string.toLowerCase()) >= 0;
    };

    return {
      rules,
      formState,
      btnCancels,
      areaOptions,
      btnok,
      areaChange,
      loadAreaData,
      title,
      area,
      formRef,
      sourceOptions,
      handleUploadChange,
      imgAction: request.BASE_URL + "/public/system/uploadImage",
      handleChange,
      fileList,
      companyOptions,
      changeCompany,
      ...toRefs(state),
      changeSource,
      filterOption,
      isAllVillage

    };
  },
});
</script>

<style lang="less" scoped>
.title-box {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  height: 40px;

  .title-left {
    height: 12px;
    width: 4px;
    border-radius: 2px;
    background-color: #2681f3;
  }

  .title {
    margin-left: 4px;
    color: #333;
  }
}
</style>
